//
//  UIButton.swift
//  Networking
//
//  Created by 许必成 on 2020/7/22.
//  Copyright © 2020年 东信北邮信息技术有限公司. All rights reserved.
//

import UIKit

enum ImagePositionStyle {
    /// 图片在左，文字在右
    case left
    /// 图片在右，文字在左
    case right
    /// 图片在上，文字在下
    case top
    /// 图片在下，文字在上
    case bottom
}

class kButton: UIButton {
    
    var space: CGFloat = 10
    
    var imageStyle = ImagePositionStyle.top
    
    open override func layoutSubviews() {
        super.layoutSubviews()
        
        /// titleLabel的宽度
        let titleW = titleLabel?.bounds.width
        /// titleLabel的高度
        let titleH = self.titleLabel?.bounds.height
        /// imageView的宽度
        let imageW = self.imageView?.bounds.width
        /// imageView的高度
        let imageH = self.imageView?.bounds.height
        /// 按钮中心点X的坐标（以按钮左上角为原点的坐标系）
        let btnCenterX = self.bounds.width/2
        /// imageView中心点X的坐标（以按钮左上角为原点的坐标系）
        let imageCenterX = btnCenterX - titleW!/2
        /// titleLabel中心点X的坐标（以按钮左上角为原点的坐标系）
        let titleCenterX = btnCenterX + imageW!/2
        
        switch imageStyle {
            
        case .left:
            self.titleEdgeInsets = UIEdgeInsets(top: 0, left: space/2, bottom: 0,  right: -space/2)
            self.imageEdgeInsets = UIEdgeInsets(top: 0, left: -space/2, bottom: 0, right: space)
            
        case .right:
            self.titleEdgeInsets = UIEdgeInsets(top: 0, left: -(imageW! + space/2), bottom: 0, right: imageW! + space/2)
            self.imageEdgeInsets = UIEdgeInsets(top: 0, left: titleW! + space/2, bottom: 0, right: -(titleW! + space/2))
            
        case .top:
            self.titleEdgeInsets = UIEdgeInsets(top: imageH!/2 + space/2, left: -(titleCenterX-btnCenterX), bottom: -(imageH!/2 + space/2), right: titleCenterX-btnCenterX)
            self.imageEdgeInsets = UIEdgeInsets(top: -(titleH!/2 + space/2), left: btnCenterX-imageCenterX, bottom: titleH!/2 + space/2, right: -(btnCenterX-imageCenterX))
            
        case .bottom:
            self.titleEdgeInsets = UIEdgeInsets(top: -(imageH!/2 + space/2), left: -(titleCenterX-btnCenterX), bottom: imageH!/2 + space/2, right: titleCenterX-btnCenterX)
            self.imageEdgeInsets = UIEdgeInsets(top: titleH!/2 + space/2, left: btnCenterX-imageCenterX,bottom: -(titleH!/2 + space/2), right: -(btnCenterX-imageCenterX))
        }
    }
}


